<!-- 物流运费统计表 -->
<template>
  <div class="basic_info">
    <div class="info_operation_btn">
      <div class="btn_left">
        <el-button @click="getListBtn" style="width: 100px">查看单据</el-button>
        <!-- <el-button @click="exportExcel">导出</el-button> -->
        <el-button @click="handleShortcutKeyPrint">打印(P)</el-button>
      </div>
      <div class="btn_right">
        <el-input v-model="queryData.param" placeholder="请输入单据编号\物流公司名称\关键字搜索" />
        <el-button type="primary" @click="onQuery">搜索</el-button>
        <el-button @click="onRefresh">刷新</el-button>
        <i @click="onShowColumn()" class="set_up el-icon-s-tools"></i>
      </div>
    </div>
    <div class="info_content_div">
      <div class="div_table">
        <div class="div_screen">
          <div class="screen_left">
            <div class="custom_item">
              <div class="item_title">物流公司</div>
              <el-select
                placeholder
                v-model="queryData.expressId"
                filterable
                @change="onSelectExpress"
              >
                <el-option
                  v-for="item in wlgsOptions"
                  :key="item.id"
                  :label="item.expressName"
                  :value="item.id"
                ></el-option>
                <el-option key label value>
                  <div class="custom_add" @click.stop="onShowLogisticsAdd">
                    <i class="el-icon-plus"></i>
                    <span>新增</span>
                  </div>
                </el-option>
              </el-select>
            </div>
            <div class="custom_item">
              <div class="item_title">经手人</div>
              <el-select
                placeholder
                v-model="queryData.sysUserId"
                @change="jsrChange"
                filterable
              >
                <el-option
                  style="font-size: 12px"
                  v-for="item in jsrOptions"
                  :key="item.id"
                  :label="item.realname"
                  :value="item.id"
                ></el-option>
              </el-select>
            </div>
          </div>

          <div class="screen_right">
            <el-select @change="changeDate" v-model="monthValue">
              <el-option
                v-for="item in monthOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-date-picker
              v-model="nowDate"
              type="daterange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="onClickPicker"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
            <el-button type="primary" @click="getDataList">查询</el-button>
          </div>
        </div>

        
        <div class="table_content">
          <el-table
            ref="tableRef"
            show-summary
            :summary-method="getSummaries"
            highlight-current-row
            border
            @row-click="onClickRow"
            @row-dblclick="onRowDblclick"
            :header-cell-style="{
              color: '#666666',
              textAlign: 'center',
              height: '30px',
              borderColor: '#dddddd',
            }"
            :data="tableData"
            height="99%"
          >
            <el-table-column :resizable="false" label="序号" type="index" width="50"></el-table-column>
            <template v-for="(item, index) in columnData">
              <el-table-column
                :show-overflow-tooltip="true"
                :key="index"
                :label="item.zidingyiName ? item.zidingyiName : item.morenName"
                v-if="item.zidingyiState"
                :prop="item.props"
                min-width="150px"
                :sortable="item.sortable"
                :width="item.props == 'orderNumber' ? '170px' : ''"
              >
                <template slot-scope="scope">
                  <span v-if="item.props == 'price'">
                    {{ $formatMoney(scope.row[item.props]) }}
                  </span>
                  <span v-else>{{ scope.row[item.props] }}</span>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
        <div class="table_pagination">
          <div class="pagination_div">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="pagesize"
              layout="jumper, prev, pager,next, sizes"
              :total="tableData.length"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 列配置弹框 -->
    <CConfiguration
      ref="setColumnRef"
      :columnDataArr="columnData"
      :defaultColumnDataArr="defaultColumnData"
      orderType="物流运费统计表"
      @onSaveColumn="onSaveColumn"
    ></CConfiguration>
    <!-- 打印 -->
    <dialog-print ref="print"></dialog-print>
    <!-- 新增物流公司 -->
    <DialogDLogisticsAdd ref="dialogLogisticsAdd" @onAddSubmit="onAddLogistics"></DialogDLogisticsAdd>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import CConfiguration from '@/components/c_column/columnConfiguration1'
/**打印 */
import dialogPrint from '@/views/components/dialogPrintStatic'
import { dateStrFromDate } from '@/utils/DateFormatter'
import { postAction, getAction } from '../../../api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { handlePermissions, handleOtherPerms } from '@/utils/index'
import DialogDLogisticsAdd from '@/views/components/dialogLogisticsAdd'
import { delcommafy } from '../../../utils'
export default {
  name: 'logisticsFreightStatistics',
  components: {
    CConfiguration,
    dialogPrint,
    DialogDLogisticsAdd
  },
  mixins: [JeecgListMixin],
  computed: {
    ...mapGetters(['name']),
    buttonsPermissions () {
      return handlePermissions(this.api)
    },
    printPermissions () {
      return handleOtherPerms('单据可多次打印')
    },
  },
  created () {
    this.getData()
  },
  data () {
    return {
      // 查询条件数据
      queryData: {
        startDate: '',
        endDate: '',
        sysUserId: '', // 经手人id
        expressId: '', // 物流公司id
        param: '',
      },
      // 时间区间选择
      monthValue: '本月',
      monthOptions: [
        {
          value: '今日',
          label: '今日',
        },
        {
          value: '本周',
          label: '本周',
        },
        {
          value: '本月',
          label: '本月',
        },
        {
          value: '本年',
          label: '本年',
        },
      ],
      isShowDate: true, // 是否显示选择时间组件
      nowDate: [],
      // 表格数据
      tableData: [],
      // 列配置数据
      defaultColumnData: [],
      updateId: '', // 修改列配置时返回的id
      columnData: [
        {
          morenName: '单据日期',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'createOrderDate',
        },
        {
          morenName: '单据编号',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: false,
          props: 'orderNumber',
        },
        {
          morenName: '单据类型',
          zidingyiName: '',
          morenState: false,
          zidingyiState: true,
          noModify: true,
          props: 'orderType_dictText',
        },
        {
          morenName: '快递物流公司',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: true,
          props: 'expressId_dictText',
        },
        {
          morenName: '往来单位',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: true,
          props: 'xghCompanyId_dictText',
        },
        {
          morenName: '经手人',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: true,
          props: 'sysUserId_dictText',
        },
        {
          morenName: '运费金额',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: true,
          props: 'price',
        },
        {
          morenName: '单据状态',
          zidingyiName: '',
          morenState: true,
          zidingyiState: true,
          noModify: true,
          props: 'orderStatus_dictText',
        },
      ],
      pagesize: 20, //每页的数据条数
      currentPage: 1, //默认开始页面
      api: '物流运费统计表',
      url: {
        exportXlsUrl: '/financialstatements/operatingstatements/exportXls',
        listUrl: '/xghExpress/statement/getExpressTransportExpense',
        userList: '/dept/xghAccountBookDept/getAllDeptUsers', // 经手人列表
      },
      arr: ['salesRevenue', 'salesCost', 'settlementAmount', 'paymentAmount', 'salesGrossProfit'],
      arr1: ['salesRevenue', 'salesCost', 'settlementAmount', 'paymentAmount', 'salesGrossProfit', 'grossProfitMargin'],
      printClick: false,

      // 物流公司
      wlgsOptions: [],
      // 经手人
      jsrOptions: [],

      bankData: '', // 选中行
    }
  },
  methods: {
    /**
     * 获取物流公司列表
     */
     async getExpressList () {
      const data = await getAction('/xghExpress/xghExpress/listNoPage', {})
      if (data.code == '200') {
        this.wlgsOptions = data.result
      }
    },
    onShowLogisticsAdd () {
      this.$refs.dialogLogisticsAdd.dialogVisible = true
    },
    //新增物流公司
    onAddLogistics (val) {
      postAction('/xghExpress/xghExpress/add', val).then(res => {
        if (res.code === 200) {
          this.$elMessage({
            message: '添加成功！',
            type: 'success',
          })
          this.getExpressList()
        }else{
          this.$elMessage.error(res.message)
        }
      })
    },
    // 经手人列表
    getUserList () {
      getAction(this.url.userList,{}).then((res) => {
        if (res.code == 200) {
          this.jsrOptions = res.result
          this.totalPersons = res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 打印
    handleShortcutKeyPrint () {
      this.printClick = true
      this.getDataList()
    },
    handlePrint () {
      // if (!this.buttonsPermissions.DaYin) {
      //   this.$elMessage.warning('未拥有打印权限！')
      // } else 
      if (!this.tableData || this.tableData.length <= 0) {
        this.$elMessage.warning('没有要打印的记录！')
      } else {
        let printData = {
          riqi: this.queryData.startDate + '~' + this.queryData.endDate,
          printExclusive: this.tableData.map(item => {
            item.price = this.$formatMoney(item.price)
            return item
          }),
        }
        // 可以多次打印设置
        if (this.printPermissions) {
          this.$refs.print.show(printData, this.columnData, this.api)
        } else {
          if (this.$lcStorage.get('printLimitValue')) {
            // 获取打印次数
            this.getPrintNum(this.api, (() => {
              this.$refs.print.show(printData, this.columnData, this.api)
            }))
          } else {
            this.$refs.print.show(printData, this.columnData, this.api)
          }
        }
      }
    },
    // 获取数据
    getData () {
      this.getTimeRange(this.$setTimeRange(5)) // 默认获取当月时间
      this.getUserList()
      this.selectTitle()
      this.getDataList(1)
      this.getExpressList()
    },
    // 初始化查询列配置值
    async selectTitle () {
      let obj = await this.$setColumn.selectColumn(this.api)
      console.log('obj', obj)
      if (obj.code === 200) {
        this.updateId = obj.updateId
        this.columnData = JSON.parse(JSON.stringify(obj.columnData))
      } else if (obj.code === 500) {
        let id = await this.$setColumn.addColumn(this.api, this.columnData)
        this.updateId = id
      }
      console.log(this.columnData);
    },
    // 触发列配置弹框
    onShowColumn () {

      // let list = []
      // for (let index = 0; index < this.columnData.length; index++) {
      //   const element = this.columnData[index];
      //   let sub = element.subset
      //   list = list.concat(sub)
      // }
      // let defaultColumnData = JSON.parse(JSON.stringify(this.$options.data().columnData))
      // let defaultList = []
      // for (let index = 0; index < defaultColumnData.length; index++) {
      //   const element = defaultColumnData[index];
      //   let sub = element.subset
      //   defaultList = defaultList.concat(sub)
      // }
      // this.$refs.setColumnRef.loadData(list, defaultList)
      this.defaultColumnData = this.$options.data().columnData
      this.$refs.setColumnRef.dialogVisible = true
    },
    // 列配置修改后数据获取
    async onSaveColumn (value) {
      this.columnData = value
      let res = await this.$setColumn.editColumn(this.api, this.columnData, this.updateId)
      if (res.code == 200) {
        this.$elMessage.success(res.message)
      } else {
        this.$elMessage.error(res.message)
      }
    },
    getDataList (page) {
      if (page == 1) {
        this.currentPage = 1
      }
      let parmas = {
        ...this.queryData,
        pageSize: this.pagesize,
        pageNo: this.currentPage,
      }
      getAction(this.url.listUrl, parmas).then(res => {
        console.log(res);
        if (res.success) {
          // let list = res.result || []
          let list = res.result.records || []
          this.tableData = list
        } else {
          this.$elMessage.error(res.message)
        }
        if (this.printClick) {
          this.handlePrint()
        }
        this.printClick = false
      })
    },
    // 判断当前选择时间段
    changeDate (val) {
      this.isShowDate = true
      switch (val) {
        case '全部':
          this.getTimeRange({
            now: '',
            end: ''
          })
          break
        case '今日':
          this.getTimeRange(this.$setTimeRange(1))
          break
        case '昨天':
          this.getTimeRange(this.$setTimeRange(2))
          break
        case '本周':
          this.getTimeRange(this.$setTimeRange(3))
          break
        case '上周':
          this.getTimeRange(this.$setTimeRange(4))
          break
        case '本月':
          this.getTimeRange(this.$setTimeRange(5))
          break
        case '上月':
          this.getTimeRange(this.$setTimeRange(6))
          break
        case '本年':
          this.getTimeRange(this.$setTimeRange(7))
          break
        case '去年':
          this.getTimeRange(this.$setTimeRange(8))
          break
        default:
          break
      }
    },
    // 获取时间范围并设置
    getTimeRange (data) {
      console.log('data', data)
      this.nowDate = [data.now, data.end]
      this.queryData.startDate = data.now
      this.queryData.endDate = data.end
    },
    // 获取当前选中时间
    onClickPicker (val) {
      this.queryData.startDate = val[0]
      this.queryData.endDate = val[1]
    },
    // 合计列计算
    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 1) {
          sums[index] = '共' + this.tableData.length + '条明细'
        } else if (this.arr1.includes(column.property)) {
          let item = data[0]
          if (item) {
            if (this.arr.includes(column.property)) {
              sums[index] = this.$formatMoney(delcommafy(item[column.property]))
            } else {
              sums[index] = item[column.property]
            }
          } else {
            sums[index] = ''
          }

        }
      })
      return sums
    },

    // 设置列配置（实现列的显示隐藏、列名修改、还原默认值；上下移动列未实现）
    setColumn () {
      let getTable = document.getElementsByClassName('table_content')[0]
      let getTr = getTable.getElementsByTagName('tr')
      getTr.forEach((item) => {
        let getTd = item.getElementsByClassName('set_order')
        getTd.forEach((item, index) => {
          // item.style.order = this.newColumnData[index].zidingyiSort
          if (this.newColumnData[index].zidingyiState == false) {
            item.style.display = 'none'
          } else {
            item.style.display = 'block'
          }
        })
      })
      let getTh = getTr[0].getElementsByClassName('set_order')
      getTh.forEach((item, index) => {
        // item.style.order = this.newColumnData[index].zidingyiSort
        if (this.newColumnData[index].zidingyiState == false) {
          item.style.display = 'none'
        } else {
          item.style.display = 'block'
        }
      })
    },
    // 获取每页几条数据
    handleSizeChange (val) {
      this.pagesize = val
      this.getDataList(1)
    },
    // 获取当前第几页
    handleCurrentChange (val) {
      this.currentPage = val
      this.getDataList()
    },
    exportExcel () {
      let queryParam = {
        ...this.queryData,
        fileName: '物流运费统计表',
      }
      this.handleExportXlsByStaff('物流运费统计表', queryParam)
    },
    // 选中当前行
    onClickRow (row) {
      this.bankData = row
    },
    // 双击跳转
    onRowDblclick(row) {
      this.bankData = row
      this.getListBtn()
    },
    // 查看单据
    getListBtn () {
      if (this.bankData) {
        console.log('this.bankData',this.bankData);
        let id = this.bankData.orderId
        let orderNumber = this.bankData.orderNumber
        if (orderNumber.indexOf('xsckd') > -1) {
          this.$router.push({ name: 'saleManage-salesBill-billSalesDelivery', params: { billId: id } })
        } else if (orderNumber.indexOf('xsthd') > -1) {
          this.$router.push({ name: 'saleManage-salesBill-billSalesReturn', params: { billId: id } })
        } else if (orderNumber.indexOf('xshhd') > -1) {
          this.$router.push({ name: 'saleManage-salesBill-billSalesExchange', params: { billId: id } })
        } else if (orderNumber.indexOf('cgthd') > -1) {
          this.$router.push({ name: 'purchaseManage-purchaseBill-billPurchaseReturn', params: { billId: id } })
        } else if (orderNumber.indexOf('cghhd') > -1) {
          this.$router.push({ name: 'purchaseManage-purchaseBill-billPurchaseExchange', params: { billId: id } })
        } else if (orderNumber.indexOf('cgrkd') > -1) {
          this.$router.push({ name: 'purchaseManage-purchaseBill-billPurchaseWarehousing', params: { billId: id } })
        } else {
          this.$elMessage.warning('暂不支持查看该单据')
        }
      } else {
        this.$elMessage.warning('请选择要查看的单据')
      }
    },
    // 查询
    onQuery() {
      this.getDataList()
    },
    // 刷新
    onRefresh() {
      Object.assign(this.$data, this.$options.data())
      // this.buttonsPermissions = handlePermissions('采购订单执行情况')
      this.getData()
    },

    onSelectExpress (val) {
      console.log('val', val)
      this.queryData.expressId = val
      console.log('this.queryData', this.queryData)
      this.getDataList(1)
    },

    jsrChange (val) {
      this.queryData.sysUserId = val
      this.getDataList(1)
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';
.basic_info {
  width: 100%;
  height: calc(100vh - 102px);
  background: #f0f2f5;
  box-sizing: border-box;
  padding: 0 0.168761rem 0.168761rem;
  display: flex;
  flex-direction: column;
}

.info_operation_btn {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  ::v-deep .el-button {
    width: 70px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    margin-right: 10px;
    margin-left: 0;
    border-radius: 0.1rem;
    border: none;
  }

  .el-button--default {
    color: #666;
    border: none;
  }

  .el-button--default:hover {
    background-color: #ffffff;
  }

  ::v-deep .el-select {
    width: 80px;
    height: 30px;
    box-sizing: border-box;
    margin-right: 0.112507rem;

    .el-input {
      .el-input__inner {
        height: 30px;
        border: none;
        font-size: 12px;
      }

      .el-input__suffix {
        height: 30px;
        display: flex;
        align-items: center;
      }
    }
  }

  ::v-deep .el-date-editor {
    width: 220px;
    height: 30px;
    background: #ffffff;
    border: 1px solid #d9d9d9;
    margin-right: 0.112507rem;
    padding: 3px 6px;

    .el-range__icon {
      position: absolute;
      right: 0;
      line-height: 30px;
    }

    .el-range-separator {
      line-height: 24px;
    }

    .el-range-input {
      font-size: 12px;
    }

    .el-range__close-icon {
      display: none;
    }
  }

  .btn_left {
    width: 60%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .btn_right {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .set_up {
      font-size: 20px;
      color: rgb(153, 153, 153);
    }
  }
}

.info_content_div {
  width: 100%;
  height: calc(100% - 60px);
  background-color: #ffffff;
  padding: 10px;

  .div_table {
    width: 100%;
    height: 100%;

    .div_screen {
      width: 100%;
      // height: 50px;
      margin-bottom: 10px;
      display: flex;
      align-items: baseline;

      .screen_left {
        font-size: 12px;
        box-sizing: border-box;
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
      }

      .screen_right {
        margin-right: 20px;
        box-sizing: border-box;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        box-sizing: border-box;

        ::v-deep .el-button {
          // width: 60px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          border-radius: 5px;
          border: none;
        }

        ::v-deep .el-select {
          width: 80px;
          margin: 0 10px;

          .el-input {
            .el-input__inner {
              height: 30px;
              border-color: #e3e3e3;
              font-size: 12px;
              padding-left: 5px;
            }

            .el-input__suffix {
              height: 30px;
              display: flex;
              align-items: center;
            }
          }
        }

        ::v-deep .el-date-editor {
          width: 220px;
          height: 30px;
          background: #ffffff;
          border: 1px solid #d9d9d9;
          margin-right: 0.112507rem;
          padding: 3px 6px;

          .el-range__icon {
            position: absolute;
            right: 0;
            line-height: 30px;
          }

          .el-range-separator {
            line-height: 24px;
          }

          .el-range-input {
            font-size: 12px;
          }

          .el-range__close-icon {
            display: none;
          }
        }
      }
    }

    .table_content {
      height: calc(100% - 110px);

      ::v-deep .el-table {
        border-color: #ddd;
        box-sizing: border-box;

        th,
        td {
          padding: 0;
          color: #666;
        }

        .el-table__header {
          tr {
            &:last-child {
              th {
                background: rgb(237, 237, 237) !important;
              }
            }
          }
        }

        .cell {
          line-height: 30px;
          font-size: 12px;
          text-align: center;
        }

        .el-table__body tr:hover > td {
          background: #e3f6ff;
        }

        .el-table__footer-wrapper {
          td {
            background: #f4f4f4;
            border: none;
          }
        }

        //滚动条的宽度
        ::-webkit-scrollbar {
          width: 8px;
          height: 10px;
          background-color: #e5e5e5;
        }

        //滚动条的滑块
        ::-webkit-scrollbar-thumb {
          background-color: #c9c9c9;
        }
      }
    }

    .table_pagination {
      width: 100%;
      height: 50px;
      box-sizing: border-box;
      padding: 10px 0;
      display: flex;

      .pagination_div {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        ::v-deep .el-pagination {
          padding: 0;
          height: 30px;

          .el-pagination__sizes {
            margin: 0;

            .el-input {
              margin-right: 0;
            }
          }
        }
      }
    }
  }
}

.custom_item {
  display: flex;
  align-items: center;
  margin: 10px 10px 10px 0;
  width: 180px;
  font-size: 12px;

  ::v-deep .el-select {
    .el-input {
      .el-input__inner {
        height: 30px;
        border-color: #e3e3e3;
        font-size: 12px;
        padding-left: 5px;
      }

      .el-input__suffix {
        height: 30px;
        display: flex;
        align-items: center;
      }
    }
  }
  
}
.item_title {
  padding: 0 5px;
  width: auto;
  min-width: 60px;
  line-height: 30px;
  color: #666666;
  text-justify: distribute-all-lines;
  /*ie6-8*/
  text-align-last: justify;
  /* ie9*/
  -moz-text-align-last: justify;
  /*ff*/
  -webkit-text-align-last: justify;
  /*chrome 20+*/
}
</style>